import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class ListViewDemo2 extends StatefulWidget {
  const ListViewDemo2({Key? key}) : super(key: key);

  @override
  _ListViewDemo2State createState() => _ListViewDemo2State();
}

class _ListViewDemo2State extends State<ListViewDemo2> {
  late ScrollController _scrollController;
  bool _floatButton = false;
  List<int> _list = [];

  @override
  void initState() {
    super.initState();
    _scrollController = ScrollController();
    _scrollController.addListener(() {
      if (_scrollController.offset >= 100 && _floatButton == false) {
        setState(() {
          _floatButton = true;
        });
      } else if (_scrollController.offset < 100 && _floatButton == true) {
        setState(() {
          _floatButton = false;
        });
      }
    });
    for (var i = 0; i < 100; i++) {
      _list.add(i);
    }
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _scrollController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('列表练习2'),
      ),
      body: Scrollbar(
        child: ListView.builder(
          // scrollDirection: Axis.horizontal,//方向：horizontal水平  ||vertical 垂直
          itemBuilder: (BuildContext context, int index) {
            if (index % 10 == 0) {
              return Icon(Icons.add);
            }
            return Text(_list[index].toString());
          },
          itemCount: _list.length,
          controller: _scrollController,
        ),
      ),
      floatingActionButton: _floatButton
          ? FloatingActionButton(
              onPressed: () {
                _scrollController.animateTo(0,
                    duration: Duration(microseconds: 300), curve: Curves.ease);
              },
              child: Icon(Icons.vertical_align_top),
            )
          : null,
    );
  }
}
